package model

import (
	"encoding/base64"
	"ginTea/structs"
	"ginTea/utils/errmsg"
	"ginTea/utils/helpers"
	"log"

	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/scrypt"
)

type User struct {
	gorm.Model
	Username    string `gorm:"type:varchar(20);not null " json:"username" validate:"required,min=1,max=12" label:"用户名"`
	Password    string `gorm:"type:varchar(20);not null " json:"password" validate:"required,min=6,max=12" label:"密码"`
	Role        string `gorm:"type:varchar(20);DEFAULT:admin" json:"role" validate:"required,min=1,max=12" label:"用户类型"`
	Avatar      string `gorm:"type:varchar(500) " json:"avatar"`
	PhoneNumber string `gorm:"type:varchar(20) " json:"phone_number"`
}

// 查询用户名是否存在
func CheckUserExist(name string) (code int) {
	var data User
	db.Select("id").Where("username=?", name).First(&data)
	if data.ID > 0 {
		return errmsg.ERROR_USERNAME_USED //1001
	}
	return errmsg.SUCCESS
}

// 新增用户
func CreateUser(data *User) int {
	data.Password = ScryptPw(data.Password)
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// 删除用户
func DeleteUser(id int) int {
	var data User
	db.Select("id").Where("id=?", id).First(&data)
	if data.ID > 0 {
		err = db.Unscoped().Where("id = ?", id).Delete(&data).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
	return errmsg.ERROR_USER_NOT_EXIST
}

// pageNum 当前页号 pageSize当前页大小
func GetUserList(page int, pageSize int, keyword string, types string) structs.JSONResponse {
	var user []User
	var total int
	var list []interface{}
	if types == "front" {
		if len(keyword) == 0 {
			// db.Find(&user).Count(&total)
			err = db.Model(&user).
				Where("role = ?", "customer").
				Count(&total).
				Limit(pageSize).
				Offset((page - 1) * pageSize).
				Find(&user).
				Error
		} else {
			err = db.Model(&user).
				Where("role = ?", "customer").
				Where("username LIKE ?", "%"+keyword+"%").
				Count(&total).
				Limit(pageSize).
				Offset((page - 1) * pageSize).
				Find(&user).
				Error
		}
	} else {
		if len(keyword) == 0 {
			// db.Find(&user).Count(&total)
			err = db.Model(&user).
				Where("role != ?", "customer").
				Count(&total).
				Limit(pageSize).
				Offset((page - 1) * pageSize).
				Find(&user).
				Error
		} else {
			err = db.Model(&user).
				Where("role != ?", "customer").
				Where("username LIKE ?", "%"+keyword+"%").
				Count(&total).
				Limit(pageSize).
				Offset((page - 1) * pageSize).
				Find(&user).
				Error
		}
	}

	if err != nil && err != gorm.ErrRecordNotFound {
		return helpers.Error("未找到数据")
	}
	for _, v := range user {
		list = append(list, v)
	}
	pageData := structs.NewPageData(list, pageSize, page, total)
	response := helpers.Success(pageData)
	return response
}

// 获取用户详情
func GetUserInfo(id int) ([]User, int) {
	var userInfo []User
	err := db.Where("id=?", id).First(&userInfo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR_GOODS_NOT_EXIST
	}
	return userInfo, errmsg.SUCCESS
}

// 编辑用户
func UpdateUser(data *User) int {
	var user User
	var maps = make(map[string]interface{})
	maps["username"] = data.Username
	maps["avatar"] = data.Avatar
	maps["role"] = data.Role
	maps["phone_number"] = data.PhoneNumber
	db.Select("ID").Where("username=? AND id !=?", data.Username, data.ID).First(&user)
	if user.ID > 0 {
		return errmsg.ERROR_USERNAME_USED
	} else {
		err = db.Model(&user).Where("id = ?", data.ID).Updates(maps).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
}
func UpdateUserByCus(data *User) int {
	var user User
	var maps = make(map[string]interface{})
	maps["username"] = data.Username
	// maps["avatar"] = data.Avatar
	maps["role"] = "customer"
	maps["phone_number"] = data.PhoneNumber
	maps["password"] = ScryptPw(data.Password)
	db.Select("id").Where("username=? AND id !=?", data.Username, data.ID).First(&user)
	if user.ID > 0 {
		return errmsg.ERROR_USERNAME_USED
	} else {
		err = db.Model(&user).Where("id = ?", data.ID).Updates(maps).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
}

// 修改密码
func UpdatePwd(data *User) int {
	var user User
	var maps = make(map[string]interface{})
	maps["password"] = ScryptPw(data.Password)
	err = db.Model(&user).Where("id = ?", data.ID).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// 密码加密
func ScryptPw(password string) string {
	const KeyLen = 10
	salt := make([]byte, 8)
	salt = []byte{4, 78, 56, 2, 62, 92, 13, 14}
	HashPw, err := scrypt.Key([]byte(password), salt, 16384, 8, 1, KeyLen)
	if err != nil {
		log.Fatal(err)
	}
	FinalPassWord := base64.StdEncoding.EncodeToString(HashPw)
	return FinalPassWord
}

// 前端登陆
func CheckLoginFront(username string, password string) (int, int) {
	var user User
	db.Where("username=?", username).First(&user)
	// 用户不存在
	if user.ID == 0 {
		return 0, errmsg.ERROR_USER_NOT_EXIST
	}
	// 密码错误
	if ScryptPw(password) != user.Password {
		return 0, errmsg.ERROR_PASSWORD_WRONG
	}
	return int(user.ID), errmsg.SUCCESS
}

// 登陆验证
func CheckLogin(username string, password string) (int, int) {
	var user User
	db.Where("username=?", username).First(&user)
	// 用户不存在
	if user.ID == 0 {
		return 0, errmsg.ERROR_USER_NOT_EXIST
	}
	// 密码错误
	if ScryptPw(password) != user.Password {
		return 0, errmsg.ERROR_PASSWORD_WRONG
	}
	if user.Role != "admin" {
		return 0, errmsg.ERROR_USER_NO_RIGHT
	}
	return int(user.ID), errmsg.SUCCESS
}
